//
//  CameraSettingVC.swift
//  WatermarkCamera
//
//  Created by 赵新 on 8/7/2024.
//

import UIKit
import AxcBedrock

// MARK: - [CameraSettingVC]

class CameraSettingVC: BaseVC {
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    convenience init(_ viewModel: CameraSettingVM) {
        self.init(nibName: nil, bundle: nil)
        self.viewModel = viewModel
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var viewModel: CameraSettingVM = .init()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.loadList()
    }

    // Internal

    lazy var tableView: UITableView = {
        // 统一注册
        var registers: [AxcRegister] = [
            AxcRegister(CameraSettingCell.self),
        ]

        // tb
        let tableView = UITableView.Axc.Create(style: .grouped,
                                               delegate: self,
                                               dataSource: self,
                                               registers: registers)
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        return tableView
    }()

    override func createUI() {
        makeNavView(showShadow: false)
        title = "相机设置"

        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindReverseAction() {
        viewModel.dataListRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }).disposed(by: rx.disposeBag)
    }

    /// 是否是自己组
    func isSelfGroup(_ section: Int) -> Bool {
        // 输入组数量
        return section == 0
    }

    /// 转换为自己组
    func transformSelfSection(_ section: Int) -> Int {
        if section == 0 {
            return section
        } else {
            return section
        }
    }

    /// 转换为自己组
    func transformSelfIndexPath(_ indexPath: IndexPath) -> IndexPath {
        return .init(row: indexPath.row, section: transformSelfSection(indexPath.section))
    }

    /// 转换为代理组
    func transformThisSection(_ section: Int) -> Int {
        return section - 1
    }

    /// 转换为代理组
    func transformDeIndexPath(_ indexPath: IndexPath) -> IndexPath {
        return .init(row: indexPath.row, section: transformThisSection(indexPath.section))
    }
}

// MARK: UITableViewDelegate

extension CameraSettingVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = transformSelfIndexPath(indexPath)
        if let group = viewModel.dataListRelay.value.axc.object(at: indexPath.section),
           let model = group.axc.object(at: indexPath.row) {
            switch model.cellType {
            // 拍摄辅助线
            case .assistLineStyle:
                var actions: [AxcBedrockLib.AlertAction] = []
                for cas in HomeControlAssistLineLayer.AssistLineStyle.allCases {
                    let action: AxcBedrockLib.AlertAction = .init(title: cas.info.name, actionBlock: { [weak self] _ in
                        guard let weakSelf = self else { return }
                        weakSelf.viewModel.updateAssistLineStyle(cas)
                    })
                    actions.append(action)
                }
                actions.append(.CancelAction(title: "取消"))
                let alert = UIAlertController.Axc.Create(title: "辅助线类型", actions: actions, style: .actionSheet)
                present(alert, animated: true)

            // 用户协议
            case .serviceAgreement:
                if let url = URL(string: "https://h5hybridprod.yupaowang.com/article-out?id=1811337856036339794") {
                    UIApplication.shared.open(url)
                }
            // 隐私政策
            case .privacyAgreement:
                if let url = URL(string: "https://h5hybridprod.yupaowang.com/article-out?id=1811337751782727750") {
                    UIApplication.shared.open(url)
                }
            default: break
            }
        }
    }
}

// MARK: UITableViewDataSource

extension CameraSettingVC: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        var count = viewModel.dataListRelay.value.count
        return count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let group = viewModel.dataListRelay.value.axc.object(at: transformSelfSection(section)) {
            return group.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = "F5F5F5".axc.uiColor
        return headerView
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return .Axc.Min
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let indexPath = transformSelfIndexPath(indexPath)
        if let group = viewModel.dataListRelay.value.axc.object(at: indexPath.section),
           let item = group.axc.object(at: indexPath.row) {
            return item.rowHeight
        }
        return 44
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CameraSettingCell = tableView.axc.dequeueReusableCell()
        let indexPath = transformSelfIndexPath(indexPath)
        if let group = viewModel.dataListRelay.value.axc.object(at: indexPath.section),
           let model = group.axc.object(at: indexPath.row) {
            cell.configModel(model)
            // 分割线
            let isNoLastSection = (indexPath.section != viewModel.dataListRelay.value.count - 1)
            let isNoLasrRow = (indexPath.row == (group.count - 1))
            cell.lineView.isHidden = isNoLastSection && isNoLasrRow
        }
        cell.switchDidChange = { [weak self] (isOn, model) in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.updateSwitchSetting(cellType: model.cellType, isOn: isOn)
            weakSelf.viewModel.loadList()
        }
        return cell
    }
}
